# -*- coding: utf-8 -*-

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later
# Isidro Catalan <icatalan@opendomo.com>


from elisa.core.utils.i18n import install_translation

from elisa.plugins.poblesec.actions import Action, LinkAction

from elisa.plugins.opendomo.models import OpendomoPhotoModel

from elisa.plugins.opendomo.utils import get_opendomo_provider

from elisa.plugins.poblesec.actions import ContextualAction



_ = install_translation('opendomo')


class LoginAction(LinkAction):
    """ L{LinkAction} leading to the Opendomo login form.
    """

    title = _('Login to Opendomo')
    path = '/poblesec/opendomo/login'


class LogoutAction(Action):
    """ Action used to clear the Opendomo resource_provider
    authentication token and go back to the previous menu. This action
    is called from the 'My Account' menu.
    """

    title = _('Logout From Opendomo')

    def run(self):
        get_opendomo_provider().logout()

        frontend = self.controller.frontend
        browser = frontend.retrieve_controllers('/poblesec/browser')[0]
        return browser.history.go_back()


class AccessAction(LinkAction):
    """ Action leading to the 'CGI' menu.
    """
    title = _('Opendomo Access')
    path = '/poblesec/opendomo/access'
    

class PlayOpendomoImageAction(ContextualAction):
    
    def execute(self, item):
        print '---EXECUTING----'
        controllers = self.controller.frontend.retrieve_controllers('/poblesec/slideshow_player')
        slideshow_controller = controllers[0]
        slideshow_controller.player.clear_playlist()

        # Cancel all currently queued requests
        for widget in self.controller.nodes._widgets:
            self.controller.cancel_deferreds(widget)

        def _failure(failure):
            # Swallow errbacks only when the deferred has been cancelled
            failure.trap(CancelledError)

        playlist = []
        global index
        index = 0

        def iterate_photos():
            for opendomo_photo in self.controller.model:
                print '---ITERATING----'
                if not isinstance(opendomo_photo, OpendomoPhotoModel):
                    continue
                if opendomo_photo == item:
                    global index
                    index = len(playlist)
                try:
                    image_model = opendomo_photo.image_model
                except AttributeError:
                    image = ImageModel()
                    image.can_rotate = False
                    try:
                        image.references.append(opendomo_photo.thumbnail_uri)
                    except AttributeError:
                        image.references.append(opendomo_photo.image_uri)
                    image.references.append(opendomo_photo.image_uri)
                    opendomo_photo.image_model = image

                photo = opendomo_photo.image_model
                photo.title = opendomo_photo.title or \
                              '<%s>' % opendomo_photo.opendomo_id
                playlist.append(photo)
                yield opendomo_photo

        def playlist_filled(result):
            slideshow_controller.player.set_playlist(playlist, index)

            controllers = self.controller.frontend.retrieve_controllers('/poblesec')
            main = controllers[0]
            main.show_slideshow_player()

        dfr = task.coiterate(iterate_photos())
        dfr.addCallback(playlist_filled)
        return dfr
